package com.knowledge.plus.多线程.锁.显示锁;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 * 读锁（共享锁）：允许多个线程同时读取（readLock().lock()）
 * 写锁（独占锁）：同一时刻只允许一个线程写入（writeLock().lock()）
 *
 * @author TPF
 * @since 2025/6/9
 */
public class ReentrantReadWriteLockDemo {

    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private String data = "";

    public String readData() {
        rwLock.readLock().lock(); // 获取读锁
        try {
            return data;
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public void writeData(String newData) {
        rwLock.writeLock().lock(); // 获取写锁
        try {
            data = newData;
        } finally {
            rwLock.writeLock().unlock();
        }
    }

}
